// 用户相关API接口
import type { UserInfo } from '@/store/user'

// 模拟API请求延迟
const delay = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))

// 模拟API响应数据
interface ApiResponse<T> {
  code: number
  message: string
  data: T
}

// 登录请求参数
interface LoginRequest {
  mobile: string
  code: string
}

// 注册请求参数
interface RegisterRequest {
  mobile: string
  code: string
  password: string
}

// 登录响应数据
interface LoginResponse {
  token: string
  userInfo: UserInfo
}

// 发送验证码
export async function sendSmsCode(mobile: string): Promise<ApiResponse<null>> {
  // 模拟网络请求
  await delay(1000)
  
  // 简单的手机号验证
  const mobileReg = /^1[3-9]\d{9}$/
  if (!mobileReg.test(mobile)) {
    return {
      code: 400,
      message: '手机号格式不正确',
      data: null
    }
  }
  
  // 模拟发送成功
  return {
    code: 200,
    message: '验证码发送成功',
    data: null
  }
}

// 用户登录
export async function login(data: LoginRequest): Promise<ApiResponse<LoginResponse | null>> {
  // 模拟网络请求
  await delay(1500)
  
  // 简单验证
  if (!data.mobile || !data.code) {
    return {
      code: 400,
      message: '手机号或验证码不能为空',
      data: null
    }
  }
  
  // 模拟登录成功返回的数据
  const response: ApiResponse<LoginResponse> = {
    code: 200,
    message: '登录成功',
    data: {
      token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
      userInfo: {
        id: '10001',
        mobile: data.mobile,
        nickname: '用户' + data.mobile.slice(-4),
        avatar: '/static/avatar.png',
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
        balance: 100.00,
        points: 100,
        isVip: false
      }
    }
  }
  
  return response
}

// 用户注册
export async function register(data: RegisterRequest): Promise<ApiResponse<LoginResponse | null>> {
  // 模拟网络请求
  await delay(1500)
  
  // 简单验证
  if (!data.mobile || !data.code || !data.password) {
    return {
      code: 400,
      message: '手机号、验证码或密码不能为空',
      data: null
    }
  }
  
  if (data.password.length < 6) {
    return {
      code: 400,
      message: '密码至少6位',
      data: null
    }
  }
  
  // 模拟注册成功返回的数据
  const response: ApiResponse<LoginResponse> = {
    code: 200,
    message: '注册成功',
    data: {
      token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
      userInfo: {
        id: '10001',
        mobile: data.mobile,
        nickname: '用户' + data.mobile.slice(-4),
        avatar: '/static/avatar.png',
        token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
        balance: 0,
        points: 0,
        isVip: false
      }
    }
  }
  
  return response
}

// 获取用户信息
export async function getUserInfo(): Promise<ApiResponse<UserInfo | null>> {
  // 模拟网络请求
  await delay(1000)
  
  // 模拟获取用户信息
  const response: ApiResponse<UserInfo> = {
    code: 200,
    message: '获取成功',
    data: {
      id: '10001',
      mobile: '13800138000',
      nickname: '张三',
      avatar: '/static/avatar.png',
      token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9',
      balance: 100.00,
      points: 100,
      isVip: true
    }
  }
  
  return response
}